<template>
	<eui-background type="common">
		<eui-navbar ref="EuiNavBar" :title="title" :storeName="sUserStoreName" :storeId="sUserStore"
			displayable="true" />
		<view class="top-view" v-if="origData.main.c_status === '0'">
			<eui-search-bar ref="RdsSearchBar" v-model="searchText" placeholder="请输入商品条码、编码" leftIcon="icon-saoyisao"
				@confirm="searchConfirm" @leftIconClick="clickScanRight" radius="30"  :focus="true" maxlength="30">
			</eui-search-bar>
		</view>
		<eui-card hPadding="28">
			<eui-card-input v-model="currentMain.c_store_id" title="机构:" h-padding="0" type="textname2"
				:name="getName('rdsStores', currentMain.c_store_id)" ref="cardStoreInput" isBlur alignType="left"
				required="true" :rightIconType="origData.details.length > 0 ? '' : 'right'"
				@iconClick="clickRight('c_store_id')" @confirm="validateMain('c_store_id', currentMain.c_store_id)" />
			<eui-card-input v-model="currentMain.c_adno" title="部门" h-padding="0" type="textname2"
				:name="getName('rdsDeparts', currentMain.c_adno)" ref="cardAdnoInput" isBlur alignType="left"
				required="true" :rightIconType="origData.details.length > 0 ? '' : 'right'"
				@iconClick="clickRight('c_adno')" @confirm="validateMain('c_adno', currentMain.c_adno)" />
			<eui-card-input v-model="currentMain.c_wno" title="仓库" h-padding="0" type="textname2"
				:name="getName('rdsWnos', currentMain.c_wno)" ref="cardWnoInput" isBlur alignType="left" required="true"
				:rightIconType="origData.details.length > 0 ? '' : 'right'" @iconClick="clickRight('c_wno')"
				@confirm="validateMain('c_wno', currentMain.c_wno)" />
			<eui-card-input v-model="currentMain.c_ret_kind" title="退货性质" :range="selectRange.c_ret_kind"
				placeholder="请选择退货性质" h-padding="0" alignType="left" type="selector"
				:displayable="origData.details.length > 0"
				:rightIconType="origData.details.length > 0 ? '' : 'right'" />
			<eui-card-input v-model="currentMain.c_ret_priv" title="退货权限" :range="selectRange.c_ret_priv"
				placeholder="请选择退货权限" h-padding="0" alignType="left" type="selector"
				:displayable="origData.details.length > 0"
				:rightIconType="origData.details.length > 0 ? '' : 'right'" />
			<view style="width: 100%; height: 16rpx" />
			<eui-text type="price2" title="售价金额" :value="origData.main.c_at_sale" />
			<view class="item-view">
				<eui-text type="name2" title="总计(行)" :value="total_line" />
				<eui-text type="name2" title="数量总计" :value="total_num" />
			</view>
		</eui-card>
		<view class="footer-view" :style="{ height: listHeight + 'rpx' }">
			<scroll-view scroll-y="true" style="height: 100%;">
				<view style="display:flex;flex-direction: column">
					<eui-card hPadding="28" v-if="origData.details && origData.details.length > 0">
						<eui-swipe-action>
							<view :ref="'dataItem' + index" v-for="(item, index) in origData.details" :key="index"
								@click="openPopupGoodsInfo(item)">
								<eui-swipe-actionitem :ref="`swipeActionItem${index}`" :right-options="options"
									show="none" :auto-close="true" @change="change" @click="bindClick($event, index)"
									:disabled="origData.main.c_status != '0'">
									<view class="item-view">
										<eui-text type="name2"
											:value="index + 1 + '. ' + '[' + item.c_gcode + ']' + item.c_gname"
											cWidth="width: 100%" />
										<eui-text type="name2" :value="item.c_barcode" title="条码" />
										<eui-text type="slash2" :value="item.c_req_pack.toFixed(3)"
											:name="item.c_req_unit" title="包装/单位" />
										<eui-text type="price2" title="售价" :value="item.c_price"
											:valueStyle="showRightStyle" />
										<eui-text type="price2" title="申请数量" :value="item.c_n"
											:valueStyle="showRedStyle" />
										<eui-text v-model="JSON.parse(item.c_err_msg)[0].c_msg_err" type="name2"
											v-if="item.c_err_msg" title="错误:"
											cWidth="width: 100%;margin: 10rpx 0 10rpx 0" valueStyle="color: #FF4000;" />
									</view>
								</eui-swipe-actionitem>
							</view>
						</eui-swipe-action>
					</eui-card>
				</view>
			</scroll-view>
		</view>
		<view class="bottom-view">
			<view class="center-style">
				<eui-button type="max2" title="保存" singleTag="保存" @buttonClick="buttonClick"
					:disabled="!(origData.main.c_status == '0' && origData.details.length > 0)" />
				<view class="gap-view" />
				<eui-button type="max" title="审核" singleTag="审核" @buttonClick="buttonClick"
					:disabled="!(origData.main.c_status == '0' && origData.details.length > 0)" />
			</view>
		</view>
		<eui-popup ref="gdsPopup" background-color="#f8f8f8" type="bottom" :mask-click="false">
			<view class="popup-content">
				<view style="padding: 20rpx 20rpx 0 20rpx">
					<view class="item-view">
						<eui-text :value="'[' + currentGds.c_gcode + ']' + currentGds.c_name" type="name2" title="商品"
							cWidth="width: 100%" />
						<eui-text :value="getName('rdsProviders', currentGds.c_provider)" type="name2" title="供应商"
							cWidth="width: 100%" />
						<eui-text v-model="currentGds.c_barcode" type="name2" title="条码" />
						<eui-text :value="currentGds.c_content" :name="currentGds.c_unit" type="slash2" title="包装/单位" />
						<eui-text v-model="currentGds.c_con_no" type="name2" title="合同号" />
						<eui-text :value="currentGds.c_price" type="price2" title="售价" :valueStyle="showRightStyle" />
					</view>
					<view class="item-view" v-if="origData.main.c_status != '0'">
						<eui-text :value="currentGds.c_n" type="price2" title="申请数量" style="color:red"
							:valueStyle="showRedStyle" />
						<eui-text v-model="currentGds.c_serial_no" type="name2" title="批号" occupy
							cWidth="width: 100%" />
						<eui-text v-model="currentGds.c_reason" type="name2" title="报损原因" occupy cWidth="width: 100%" />
						<eui-text v-model="currentGds.c_note" type="name2" title="备注" occupy
							cWidth="width: 100%; margin-bottom: 20rpx" :valueStyle="noteStyle" />
					</view>
					<view v-if="origData.main.c_status == '0'">
						<eui-card-input v-model="currentGds.c_n" type="number" title="申请数量" :required="true"
							fieldName="c_n" @confirm="validateDetail" isBlur ref="gdsNum" placeholder="请输入申请数量"
							maxlength="9" alignType="left" :focus="true" />
						<eui-card-input v-model="currentGds.c_reason" title="报损原因" type="selector"
							:range="reasonSelectList" alignType="left" fieldName="c_reason" placement="top"
							placeholder="请选择原因" rightIconType="right" />
						<eui-card-input v-model="currentGds.c_serial_no" type="text" @confirm="validateDetail"
							title="批号" isBlur fieldName="c_serial_no" maxlength="60" alignType="left"
							:displayable="!['1', '2'].includes(currentGds?.c_sn_method)" />
						<eui-card-input v-model="currentGds.c_note" title="备注" isBlur fieldName="c_note" maxlength="100"
							alignType="left" />
					</view>
				</view>
				<view class="popup-bottom flex-1 flex">
					<eui-button type="max2" title="关闭" singleTag="关闭" @buttonClick="buttonClick"></eui-button>
					<eui-button type="max" title="确认" singleTag="确认" @buttonClick="buttonClick"
						:disabled="origData.main.c_status != '0'"></eui-button>
				</view>
			</view>
		</eui-popup>
	</eui-background>
</template>

<script setup type="ts">
	import {onMounted, ref, reactive, computed} from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { validateStores, validateGds, defaultMapping, validateStoresAndWno,ValiSerialGcode  } from '@/hooks/useValidateMethod';
import { todayAdd, formatNow } from '@/hooks/useUtils';
import service from "@/common/service";
import { getRdsUrl, rdsRequest, rdsRequestAsync } from '@/hooks/rdsServices';
import { calcAtInByPt, validateOddLot, round, calcPtInByPtPay, calcPetpayByPtPay } from '@/hooks/useCalculateMethod';
import { useMainStore } from "@/store/modules/store";
import { useLoginStore } from "@/store/modules/useLoginStore";
import { getRelatedName, getDictName, getUserDictSelectList, getDictSelect, getDictSelectList, getWeightUnits, getDictList } from '../components/RelatedName.js';
import { init, getRdsUserDepartAuthority, getRdsSysConfig } from '@/hooks/init';
import dateRangUtil from "@/common/dateRangUtil";
import { validateAdnoLevel } from '@/hooks/useBillInfo';
import Enjoy from "@/common/enjoy";
import { getDcStoreInfo } from '@/hooks/useDcStoreInfo';
import { billAudit, billSaveNew, billsDelete, billType, billKind } from "./app.js";
const mainStore = useMainStore();
const LoginStore = useLoginStore();
const rdsUrl = getRdsUrl();
const listHeight = ref(300);
const showRightStyle = ref('text-align: right');
const showRedStyle = ref('text-align: right;color: #FF4000;');
const noteStyle = ref('white-space: nowrap;overflow: hidden;text-overflow: ellipsis');
const gdsPopup = ref(null);
const RdsSearchBar = ref(null);
const gdsNum = ref(null);
const isOpened = ref('none');
const options = ref([{
  text: '删除',
  style: {
    backgroundColor: '#F56C6C',
  }
}]);
const title = ref('退货申请');
const reasonSelectList = ref([]);  //申请原因
const sUserStore = ref('');
const sUserStoreName = ref('');
const c_id = ref(''); // 单据号
const currentMain = ref({
  c_id: '',
  c_bill_type: billType,
  // c_status: '',
  c_mk_type: '3',
  c_gmode: '',
  c_property_group: '',
  c_store_name: '',
  c_store_name_en: '',
  c_wname: '',
  c_ret_class: '',
  c_inv_proc_mode: 'P',
  c_inv_lock: '0',
  c_buy_userno: '',
  c_org_no: '',
  c_charge_userno: '',
  c_pro_type: '',
  c_at_req: 0,
  c_at_disc: 0,
  c_at_sale: 0, // 售价金额
  c_process_status: 'N',
  c_mk_store_id: '',
  c_mk_store_name: '',
  c_mk_store_name_en: '',
  c_mk_dt: undefined,
  c_mk_userno: '',
  c_mk_username: '',
  c_modify_userno: '',
  c_approve_status: '1',
  c_au_userno: '',
  c_void_userno: '',
  c_print_userno: '',
  c_print_n: 0,
  c_src_id: '',
  c_src_type: '',
  c_sys_note: '',
  c_store_id: '', // 机构
  c_adno: '', // 部门
  c_wno: '', // 仓库
  c_ret_kind: '', // 退货性质
  c_ret_priv: '', // 退货权限
  c_note: '', // 备注
}); // 新增/修改主表信息
const currentGds = ref({
  "c_n": 0,
}); // 新增/修改商品信息
const currentGdsIndex = ref(0);
const dataList = ref([]); // 商品缓存信息
const origData = ref({
  main: {
    "c_id": "",
    "c_wno": "",
    "c_adno": "",
    "c_ret_kind": "",
    "c_ret_priv": "",
    "c_at_sale": 0,
    "c_mk_userno": "",
    "c_au_userno": "",
  }, // 主表
  details: [], // 商品明显
}); // 盘点单明显
const sysConfig = ref({
  c_ret_priv: {}, // 退货权限
  c_ret_kind: {}, // 退货性质
  c_ret_class: {}, // 退货分类
  c_inv_proc_mode: {}, // 库存处理方式
  c_inv_lock: {}, // 库存锁定状态
  c_status: {}, // 单据状态
  isBarcode: 0, // 0-否 1-是，默认为否，是：启用时则支持按箱码订货，否则不支持按箱码订货
});
const selectRange = ref({
  c_ret_priv: [],
  c_ret_kind: [],
}); // 下拉选择字典
const searchText = ref(''); // 扫码信息

const total_line = computed(() => {
  return origData.value.details.length;
});
const total_num = computed(() => {
  return origData.value.details.reduce((sum, item) => sum + Number(item.c_n), 0).toFixed(2);
});
const isShowArrow = computed(() => {
  return origData.value.main?.c_status == 0 ? 'icon enjoyIcon icon-you showArrow' : '';
});
const isEdit = computed(() => {
  return ['', '0'].includes(origData.value.main?.c_status || '');
});
const isSave = computed(() => {
  return ['', '0'].includes(origData.value.main?.c_status || '') && (origData.value.details.length > 0 || dataList.value.length > 0);
});

onMounted(() => {
  getListHeight()
})

// 获取列表高度
const getListHeight = async () => {
  await uni.getSystemInfo({
    success: function (res) { // res - 各种参数
      let info = uni.createSelectorQuery().select(".footer-view");
      info.boundingClientRect(function (data) { //data - 各种参数
        //获取列表高度
        let height = res.windowHeight - data.top;
        //转换rpx
        let finalHeight = height / (res.windowWidth / 750) - 100;
        listHeight.value = finalHeight;
      }).exec()
    }
  });
};

onLoad(async ({ c_id, c_gcode, storeId }) => {
  await getSysConfig();
  const { loginInfo } = mainStore;
  if (!c_id) {
    const { sUser, sCurrentAdno } = loginInfo;
    // 初始化主信息
    origData.value.main = {
      ...currentMain.value,
      c_store_id: storeId, // 机构
      c_adno: '', // 部门
      c_wno: '00', // 仓库
      c_ret_kind: '0', // 退货性质
      c_ret_priv: '0', // 退货权限
      c_note: '', // 备注
      c_status: '0',//单据状态
      c_mk_userno: sUser, // 录入人
    };
    currentMain.value = {
      ...origData.value.main
    }
    //验证部门层级
    if (!origData.value.main.c_id) {
      if (!sCurrentAdno) {
        return;
      }
      const result = await validateAdnoLevel({ IuputData: sCurrentAdno, billKind: billKind, tenantId: loginInfo.idsToken.tenantid });
      if (result && !result.HasException) {
        const userAdno = await getRdsUserDepartAuthority();
        if (userAdno.includes(sCurrentAdno)) {
          currentMain.value.c_adno = sCurrentAdno;
          origData.value.main.c_adno = sCurrentAdno;
        }
      }
    }
  } else {
    await getData(c_id);
    currentMain.value = {
      ...origData.value.main,
    };
  }
})

const getSysConfig = async () => {
  (await getDictList("退货权限")).forEach(item => {
    sysConfig.value.c_ret_priv[item.c_id] = item.c_name;
    selectRange.value.c_ret_priv.push({
      text: item.c_name,
      value: item.c_id,
      checked: item.value == '0',
    });
  });
  (await getDictList("退货性质")).forEach(item => {
    sysConfig.value.c_ret_kind[item.c_id] = item.c_name;
    selectRange.value.c_ret_kind.push({
      text: item.c_name,
      value: item.c_id,
      checked: item.value == '0',
    });
  });
  (await getDictList("PO类单据状态")).forEach(e => {
    sysConfig.value.c_status[e.c_id] = e.c_name;
  });
  sysConfig.value.isBarcode = await getRdsSysConfig("进销存管理参数", "是否支持按箱码订货");
  //损益原因
  let reasonList = getDictSelectList('退货原因');
  reasonList.forEach(item => {
    item.value = item.text;
  });
  reasonSelectList.value = reasonList;
}

// 获取单据详情信息
const getData = async (t_cid) => {
  if (!t_cid) return;
  // 根据单据id获取明细
  const objectData = {
    BillId: t_cid,
  };
  service.enjoyShowLoading('正在加载...');
  const result = await rdsRequest(rdsUrl.scApi, '商品退货申请单', 'EnjoyBillQuery', objectData);
  origData.value.main = result.ds[0];
  origData.value.details = result.ds1;
  c_id.value = t_cid;
  title.value = t_cid + '详情';
  currentMain.value = {
    ...currentMain.value,
    ...result.ds[0],
  }
  service.enjoyHideLoading();
}

// 保存数据
const billSave = async () => {
  const { loginInfo } = mainStore;
  let billlId = '';
  if (!c_id.value) {
    // 单号生成
    const getBilllIdReq = {
      BillIdKeyValue: {
        key: "c_id",
        value: "",
      },
      BillVariable: "",
      TableName: "tb_po_ret_req",
      BillName: "商品退货申请单",
    };
    billlId = await rdsRequest(rdsUrl.mainApi, '单号生成服务', 'EnjoyGetBillId', getBilllIdReq, '511');
  } else {
    billlId = origData.value.main.c_id;
  }
  // 准备商品清单
  const newGsort = Math.max(0, ...origData.value.details.map(item => item.c_gsort), ...dataList.value.map(item => item.c_gsort));
  if (currentGds.value.c_price) {
    dataList.value.push({
      c_gsort: currentGds.value.c_gsort || newGsort + 1,
      c_id: billlId,
      c_gcode: currentGds.value.c_gcode,
      c_barcode: currentGds.value.c_barcode,
      c_type: '1',
      c_adno: currentGds.value.c_g_adno,
      c_ccode: currentGds.value.c_ccode,
      c_bcode: '',
      c_req_unit: currentGds.value.c_unit,
      c_req_pack: currentGds.value.c_content,
      c_price: currentGds.value.c_price,
      c_n_advice: 0,
      c_n: currentGds.value.c_n,
      c_provider: currentGds.value.c_provider,
      c_con_type: currentGds.value.c_con_type,
      c_con_no: currentGds.value.c_con_no,
      c_pay_type: currentGds.value.c_pay_type,
      c_d_type: currentGds.value.c_d_type,
      c_dc_store_id: currentGds.value.c_dc_store_id,
      c_wno: currentMain.value.c_wno,
      c_dc_wno: currentGds.value.c_dc_wno,
      c_modify_opl_reason: '',
      c_reason: currentGds.value.c_reason,
      c_is_bad: '0',
      c_serial_no: currentGds.value.c_serial_no,
      c_src_id: '',
      c_src_type: '',
      c_to_id: '',
      c_to_type: '',
      c_proc_status: '0',
      c_note: currentGds.value.c_note,
      c_gds_flag: currentGds.value.c_gds_flag,
      c_err_msg: '',
      _flag: currentGds.value._flag || undefined, // 删除标志
      c_tenant_id: currentMain.value.c_tenant_id || undefined,
    });
  }

  // 准备主档信息(计算总售价)
  let mainObj = undefined;
  // 过滤相同项, 并且忽略删除项
  const mergeArr = [...dataList.value.filter(item => item._flag != 'del'), ...origData.value.details.filter(item => !dataList.value.some(item2 => item2.c_gsort == item.c_gsort))];
  if (!c_id.value) {
    mainObj = {
      ...currentMain.value,
      c_id: billlId,
      c_mk_dt: dateRangUtil.formatDate(new Date(),'YYYY-MM-DD HH:mm:ss'),
      c_mk_store_id: currentMain.value.c_store_id,
      c_mk_userno: loginInfo.sUser,
      c_at_sale: Math.round(mergeArr.reduce((sum, item) => sum + Number(item.c_price) * Number(item.c_n), 0) * 100) / 100,
    };
  } else {
    mainObj = {
      ...currentMain.value,
      c_id: billlId,
      c_modify_dt: dateRangUtil.formatDate(new Date(),'YYYY-MM-DD HH:mm:ss'),
      c_modify_userno: loginInfo.sUser,
      c_at_sale: Math.round(mergeArr.reduce((sum, item) => sum + Number(item.c_price) * Number(item.c_n), 0) * 100) / 100,
    };
  }
  const objectData = {
    NewList: c_id.value ? [] : [mainObj],
    ModifiedList: c_id.value ? [mainObj] : [],
    DelList: [],
    TableName: 'tb_po_ret_req',
    PrimaryKeys: ['c_tenant_id', 'c_id'],
    ChildData: [
      {
        ChildTableName: 'tb_po_ret_req_g',
        ParentTableName: 'tb_po_ret_req',
        ChildColumnNames: ['c_id'],
        ParentColumnNames: ['c_id'],
        ChildSaveModel: {
          NewList: dataList.value.filter(item => item._flag != 'del' && item.c_gsort > newGsort),
          ModifiedList: dataList.value.filter(item => item._flag != 'del' && item.c_gsort <= newGsort),
          DelList: dataList.value.filter(item => item._flag == 'del'),
          TableName: 'tb_po_ret_req_g',
          PrimaryKeys: ['c_tenant_id', 'c_id', 'c_gsort'],
        },
        BillSet: {
          BillIdKeyValue: {
            key: 'c_id',
            value: c_id.value,
          },
          BillVariable: '',
          TableName: 'tb_po_ret_req',
          BillName: '商品退货申请单',
        },
      },
    ],
    BillSet: {
      BillIdKeyValue: {
        key: "c_id",
        value: billlId,
      },
      BillVariable: "",
      TableName: "tb_po_ret_req",
      BillName: "商品退货申请单",
    },
  };
  await billSaveNew(objectData, () => {
    getData(billlId);
    resetCurrentGds();
  });
}

// 扫码
const clickScanRight = (type) => {
  uni.scanCode({
    success: async function (res) {
      if (res.result != '' && res.result != undefined && res.result != null) {
        searchText.value = res.result;
        await searchConfirm({
          value: res.result
        });
      }
    }
  });
}

const searchConfirm = async (e) => {
  if (!e || !e.value) {
    return;
  }
  let searchValue = e.value;
  const punctuationRegex = /[\u4e00-\u9fa5]|[。，“”‘’：；？！]|[!\"#$%&'()*+,-./:;<=>?@[\\\]^_`{|}~]/;
  if (punctuationRegex.test(searchValue)) {
    uni.showToast({
      title: '输入的商品条码或编码有误，请检查！',
      icon: 'none',
      duration: 3500,
    });
    return;
  }
  if (!origData.value.main.c_adno) {
    uni.showToast({
      title: '请先选择部门！',
      icon: 'none',
      duration: 3500,
    });
    setTimeout(() => {
      clickRight('c_adno')
    }, 300);
    return;
  }
  const serialInfo = {
    gcode: searchValue,
    serialNo: '',
    sda: null,
    eda: null
  };
  const valSerialRes = await rdsRequestAsync(rdsUrl.scApi, "Rds公共服务", "ValiSerialNoRule", { storeId: currentMain.value.c_store_id, serialNo: searchValue })
  if (valSerialRes.HasException) {
    uni.showToast({
      duration: 2000,
      icon: 'none',
      title: valSerialRes.Exception.Message,
      mask: true,
    });
    return;
  } else {
    if (valSerialRes.ObjectData?.isMatchRule) {
      searchText.value = valSerialRes.ObjectData.gcode;
      serialInfo.gcode = valSerialRes.ObjectData.gcode;
      serialInfo.serialNo = searchValue;
      serialInfo.sda = valSerialRes.ObjectData.sda;
      serialInfo.eda = valSerialRes.ObjectData.eda;
    }
  }
  // 检查是否已经存在
  const itemIndex = origData.value.details.findIndex(i => i.c_barcode === searchText.value || (i.c_gcode === searchText.value && (i.c_req_pack === 1 || !('c_barcode' in i))));
  if (itemIndex !== -1) {
    uni.showToast({
      title: `商品[${searchText.value}]已经在明细中存在！`,
      icon: 'none',
      duration: 3500,
    });
    openPopupGoodsInfo(origData.value.details[itemIndex]);
    return;
  }
  const itemIndex2 = dataList.value.findIndex(i => i.c_barcode === searchText.value || (i.c_gcode === searchText.value && (i.c_req_pack === 1 || !('c_barcode' in i))));
  if (itemIndex2 !== -1) {
    uni.showToast({
      title: `商品[${searchText.value}]已经在明细中存在！`,
      icon: 'none',
      duration: 3500,
    });
    openPopupGoodsInfo(origData.value.details[itemIndex2]);
    return;
  }
  // 验证商品
  let args = { fieldName: 'c_gcode', row: {}, newValue: searchText.value };
  service.enjoyShowLoading('正在加载...');
  const result = await validateGds({
    uniqueKey: '商品退货申请单', billType: '511', args,
    head: {
      adno: origData.value.main.c_adno,
      code: [origData.value.main.c_store_id],
      level: '1',
      login_store: origData.value.main.c_store_id,
      value_mode: "F",
    },
    listManager: [],
    mapping: [
      ...defaultMapping,
      //分店信息
      ['c_basic_unit', 'c_basic_unit'],
      ['c_tax_rate', 'c_tax_rate'],
      ['c_type', 'c_type'],
      ['c_unpack', 'c_unpack'],
      ['c_content', 'c_content'],
      ['c_req_unit', 'c_unit'],
      ['c_n_disp', 'c_dnlmt_number'],         //最佳货位量 ，字段不一致
      ['c_dnlmt_day', 'c_dnlmt_day'],         //安全库存天数
      ['c_min_to_order', 'c_n_min_order'],    //补货点，字段不一致
      ['c_n_min', 'c_n_min'],
      ['c_n_max', 'c_n_max'],
      //采购信息
      ['c_con_no', 'c_con_no'],
      ['c_provider', 'c_provider'],
      ['c_con_type', 'c_con_type'],
      ['c_pt_in', 'c_pt_in'],
      ['c_pt_pay', 'c_pt_pay'],
      ['c_pt_pay_con', 'c_pt_pay_con'],
      ['c_pet_pay', 'c_pet_pay'],
      ['c_pt_type', 'c_pt_type'],
      ['c_disc_rate', 'c_disc_rate'],
      ['c_tax_src', 'c_tax_src'],
      ['c_tax_rate_pay', 'c_tax_rate_pay'],
      ['c_deduct_rate', 'c_deduct_rate'],
      ['c_dc_store_id', 'c_dc_store_id'],
      ['c_dc_wno', 'c_dc_wno'],
      ['c_dc_ret_wno', 'c_dc_ret_wno'],
      ['c_pro_status', 'c_pro_status'],
      ['c_pt_pay_pop', 'c_pro_pt_pay'],      //促销进价（含税）,字段不一致
      ['c_pro_name', 'c_pro_name'],
      ['c_pro_period', 'c_pro_period'],

      ['c_min_order_n', 'c_min_order_n'],     //最小订量
      //合同信息
      ['c_pay_type', 'c_pay_type'],           //结算方式
      //商品分店信息统计信息
      ['c_lastsale_dt', 'c_lastsale_dt'],
      ['c_firstorder_dt', 'c_firstorder_dt'],
      ['c_init_disc', 'c_init_disc'],
      ['c_init_qtty', 'c_init_qtty'],
      ['c_dms', 'c_dms'],
      ['c_pdms', 'c_pdms'],
      ['c_n', ''],                            //c_n是过程up_chk_bill_rule里输出的条码含量，这里需要特殊处理下不要取过程返回的
      ['c_sn_lastweek', 'c_sn_lastweek'],     //TODO:上周销量，没有数据源

      //库存信息
      ['c_n_inv', 'c_n_inv'],                 //TODO:库存数量 没有数据源
      ['c_n_inv_bad', 'c_n_inv_bad'],         //TODO:坏货数量 没有数据源
      ['c_n_onway_in', 'c_n_onway_in'],       //TODO:入库在途数量 没有数据源
      ['c_n_onway_out', 'c_n_onway_out'],     //TODO:出库在途数量 没有数据源
      ['c_sellout_days', 'c_sellout_days'],   //TODO:可销天数=库存数量/DMS 没有数据源
      ['c_n_inv_dc', 'c_ext1'],           //TODO:配送中心库存数量 没有数据源

      //订货参数
      ['c_uplmt_day', 'c_buy_weeks'],       //
      //['c_expect_dt', 'c_expect_dt'],
    ],
    callback: async (items) => {
      items.forEach(item => {
        //
        if (item.c_price) {
          currentGds.value = item;
					currentGds.value.c_serial_no = serialInfo.serialNo;
        }
        item.c_content = sysConfig.value.isBarcode == '1' ? item.c_n : item.c_content;
      });
      return true;
    },

  });
  service.enjoyHideLoading();
  if (result) {
    setTimeout(() => {
      gdsPopup.value.open();
      // _this.$refs.gdsNum.getFocus();
    }, 300);
  } else {
    // setTimeout(() => {
    //   this.$refs.RdsSearchBar.clearIcon({ type: 'clear' });
    //   this.$refs.RdsSearchBar.focus();
    // }, 300);
  }
}

const buttonClick = async (t) => {
  const { loginInfo } = mainStore;
  let { singleTag } = t;
  switch (singleTag) {
    case '保存':
      await billSave();
      break;
    case '审核':
      billAudit({
        BillId: c_id.value,
        UserNo: loginInfo.sUser,
      }, () => {
        getData(c_id.value);
      });
      break;
    case '关闭':
      gdsPopup.value.close();
      if (RdsSearchBar.value) {
        RdsSearchBar.value.clear();
      }
      break;
    case '确认':
      let { c_n,c_serial_no } = currentGds.value;
      if (c_n < 0 || c_n > 999999) {
        uni.showToast({
          duration: 3500,
          icon: 'none',
          title: '[申请数量]必须在0和999999之间！'
        });
        setTimeout(() => {
          gdsNum.value.getFocus();
        }, 300);
        return;
      }
	  if(c_serial_no){
			console.log('11111111111111111')
		  const param = {
		  							storeId: currentMain.value.c_store_id,
		  							adno: currentMain.value.c_adno,
		  							wno: currentMain.value.c_wno,
		  							gcode: currentGds.value.c_gcode,
		  							serialNo: currentGds.value.c_serial_no
		  						};
		  		const checkResult = await ValiSerialGcode(param);
		  		if(checkResult.validated){
		  			currentGds.value.c_serial_no=checkResult.retValue;
		  		}
		  		else{
		  			uni.showToast({
		  			  duration: 3000,
		  			  icon: 'none',
		  			  title: checkResult.message,
		  			  mask: true,
		  			});
		  			currentGds.value.c_serial_no="";
					return;
		  		}
	  }

      await billSave();
      gdsPopup.value.close();
      break;
  }
}

// 选择框点击事件
const clickRight = (type) => {
  let parms = Enjoy.GetDialogParms();
  parms.CallBack = SelectionChanged;
  if (type == 'c_store_id') {
    parms.SelectionType = "机构选择";
    parms.SelectedItems = currentMain.value.c_store_id;
  } else if (type == 'c_adno') {
    parms.SelectionType = "部门选择";
    parms.SelectedItems = currentMain.value.c_adno;
  } else if (type == 'c_wno') {
    parms.SelectionType = "仓库选择";
    parms.SelectedItems = currentMain.value.c_wno;
    parms.SelectionStoreId = sUserStore.value;
  }
  Enjoy.OpenDialog(parms)
}

const validateMain = async (t, e) => {

};

const SelectionChanged = async (e) =>{
  const { loginInfo } = mainStore;
  if (e.SelectionType=='部门选择') {
    //验证部门层级
    let curAdno = e.BackParms.Key;
    const validateResult = await validateAdnoLevel({ IuputData: curAdno, billKind: billKind, tenantId: loginInfo.idsToken.tenantid });
    if (validateResult && validateResult.HasException) {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: validateResult.Exception.Message
      });
      setTimeout(() => {
        clickRight('c_adno')
      }, 1000);
      return;
    }
    const userAdno = await getRdsUserDepartAuthority();
    if (userAdno.includes(curAdno)) {
      currentMain.value.c_adno = curAdno;
      origData.value.main.c_adno = curAdno;
      if (!!searchText.value) {
        await searchConfirm(searchText.value);
      }
    } else {
      uni.showToast({
        duration: 3500,
        icon: 'none',
        title: `没有部门${curAdno}权限！`
      });
      setTimeout(() => {
        clickRight('c_adno')
      }, 1000);
      return
    }
  } else if (e.SelectionType=='机构选择') {
    let curStoreId = e.BackParms.Key;
    const result = await validateStoresAndWno({ value: curStoreId, wno: currentMain.value.c_wno });
    if (result) {
      const result = await validateStores(
          { fieldName: 'c_store_id', row: currentMain.value, newValue: curStoreId },
          { ischecklimit: true, firstValueMode: true }
      );
      if (['2', '3'].includes(result.c_type)) {
        // 更新机构信息
        sUserStoreName.value = e.BackParms.Value;
        sUserStore.value = curStoreId;
        currentMain.value.c_store_id = curStoreId;
        currentMain.value.c_mk_store_id = curStoreId;
        origData.value.main.c_store_id = curStoreId;
        origData.value.main.c_mk_store_id = curStoreId;
      } else {
        uni.showToast({
          duration: 3500,
          icon: 'none',
          title: '请选择分店或配送中心！'
        });
        setTimeout(() => {
          clickRight('c_store_id')
        }, 300);
      }
    } else {
      currentMain.value.c_wno = '';
    }
  } else if (e.SelectionType=='仓库选择') {
    currentMain.value.c_wno = e.BackParms.Key;
    origData.value.main.c_wno = e.BackParms.Key;
  }
}

const onClickGdsInfo = (item, index) => {
  service.enjoyShowLoading('正在加载...');
  try {
    currentGdsIndex.value = index;
    currentGds.value = JSON.parse(JSON.stringify(item));
    currentGds.value.rowType = (currentGds.value.rowType === 1 || currentGds.value.rowType === undefined) ? 1 : 2;
    gdsPopup.value.open();
  } catch (error) {
    service.enjoyHideLoading();
  }
  service.enjoyHideLoading();
}

const validateDetail = async(args) => {
  const { type, fieldName, oldValue, newValue, itemIndex } = args;
  let result = null;
  switch (fieldName) {
    case 'c_n':
      currentGds.value.c_n = parseFloat(newValue.toFixed(2));
      break;
	case 'c_serial_no':
		const param = {
		                    storeId: currentMain.value.c_store_id,
		                    adno: currentMain.value.c_adno,
		                    wno: currentMain.value.c_wno,
		                    gcode: currentGds.value.c_gcode,
		                    serialNo: newValue.toString()
		                };
		const checkResult = await ValiSerialGcode(param);
		if(checkResult.validated){
			currentGds.value.c_serial_no=checkResult.retValue;
		}
		else{
			uni.showToast({
			  duration: 3000,
			  icon: 'none',
			  title: checkResult.message,
			  mask: true,
			});
			currentGds.value.c_serial_no="";
		}
	  break;
  }
}

const change = (e) => {
  isOpened.value = e;
}

const bindClick = (e, index) => {
  currentGds.value = origData.value.details[index];
  uni.showModal({
    title: ' 提示',
    content: '您确定要删除数据吗？',
    showCancel: true,
    success: async (res) => {
      if (res.confirm) {
        currentGds.value = {
          ...currentGds.value,
          _flag: 'del',
        };
        await billSave();
      }
    }
  });
}

// 修改商品明细
const openPopupGoodsInfo = (e) => {
  // if (origData.value.main.c_status != 0) return;
  currentGds.value = {
    ...e,
    c_name: e.c_gname,
    c_unit: e.c_req_unit,
    c_content: e.c_req_pack,
    c_g_adno: e.c_adno,
  };
  c_id.value = e.c_id;
  setTimeout(() => {
    gdsPopup.value.open();
  }, 300);
}

// 重置当前商品
const resetCurrentGds = () => {
  // 清空搜索商品及重置当前商品
  currentGds.value = {
    c_gcode: '',
    c_barcode: '',
    c_name: '',
    c_name_en: '',
    c_g_adno: '',
    c_ccode: '',
    c_provider: '',
    c_con_no: '',
    c_con_type: '',
    c_pay_type: '',
    c_d_type: '',
    c_dc_store_id: '',
    c_dc_wno: '',
    c_reason: '',
    c_gds_flag: '',
    c_price: 0,
    c_n: 0,
  };
  dataList.value = [];
  searchText.value = '';
}

const getName = (key, value) => {
  if (!value) {
    return ''
  }
  let list = [];
  value.split(',').map(item => {
    list.push("[" + item + "]" + (getRelatedName(key, item) || key));
  })
  return list.join(',');
}
</script>

<style lang="scss" scoped>
	@import '../../../main.scss';

	.top-view {
		width: 100%;
		height: 88rpx;
	}

	.extra-view {
		margin-right: 30rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		width: 60rpx;
		height: 100%;
	}

	.footer-view {
		width: 100%;
		flex: 1;
	}

	.list-scroll {
		width: 100%;
		height: 100%;
		box-sizing: border-box;
	}

	.bottom-view {
		width: 100%;
		height: 100rpx;
		background: #FFFFFF;
		display: flex;
		justify-content: flex-end;
		align-items: center;
		flex-direction: row;
	}

	.center-style {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100%;
		margin-right: 20rpx;
		//gap: 20rpx;
	}

	.gap-view {
		width: 20rpx;
		height: auto;
	}

	//内容行
	.item-view {
		display: flex;
		flex-wrap: wrap;
		flex-direction: row;
		align-items: center;
		margin-top: 16rpx;
		row-gap: 8rpx;
	}

	.line-view {
		width: 100%;
		height: 1rpx;
		background: #EEEEEE;
		margin: 20rpx 0;
	}

	.popup-content {
		align-items: center;
		justify-content: left;
		flex-direction: column;
		padding: 0;
		width: 100%;
		background-color: #ffffff;
	}

	.popup-bottom {
		background: #ffffff;
		border-top: 1rpx solid $uni-line-color;
		display: flex;
		justify-content: center;
		padding: 20rpx;
	}
</style>
